/**
 * 
 */
package com.heer.RD.projecthour.page;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitButton;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;

import com.heer.RD.projecthour.component.DeptChoice;
import com.heer.RD.projecthour.component.ProjChoice;
import com.heer.RD.projecthour.component.StaffChoice;
import com.heer.RD.util.SecurityFacade;
import com.heer.RD.util.UtilsMisc;
import com.heer.joss.persistence.convention.ExpressionUtil;


/**
 * @author ZhaoZehui
 *
 */
public class PersonStatPage extends BasePage {

	public final static String userProjCostDetailSql = "select reg_date,hour_cost,reg_memo from user_hour u where ${criteria} order by reg_date desc";
	/**
	 * 
	 */
	public PersonStatPage(PageParameters para) {
		
		String currDateStr = UtilsMisc.getCurrDateStr();
	
		final List<Map> projStatList = new ArrayList();
		
		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackPanel");
		
		final TextField beginDate = new TextField("beginDate", new Model<String>(""));
		beginDate.setMarkupId("beginDate").setOutputMarkupId(true);
		final TextField endDate = new TextField("endDate", new Model<String>(currDateStr));
		endDate.setMarkupId("endDate").setOutputMarkupId(true);
		
		final Label selectedDate = new Label("selectedDate", "<至"+currDateStr+">");
		selectedDate.setMarkupId("selectedDate").setOutputMarkupId(true);;

		final Form f = new Form("thisForm", new CompoundPropertyModel(new ValueMap())) {
			protected void onSubmit() {
				final ValueMap values = (ValueMap)getModelObject();
				
				
				
			}
		};

		
		add(selectedDate);
		
		final WebMarkupContainer projStatListPanel = new WebMarkupContainer("projStatListPanel");
		projStatListPanel.setOutputMarkupId(true);
		
		projStatListPanel.add(new ListView("projList", projStatList) {
			protected void populateItem(final ListItem item) {
				
				final Map row = (Map)item.getModel().getObject();
				
				item.add(new Label("beginDate", new PropertyModel(item.getModel(), "BEGIN_DATE")));
				item.add(new Label("allCost", new Model<String>(UtilsMisc.transHour(new PropertyModel(item.getModel(), "HOUR_COST").getObject()))));
				
				Label projIdx = new Label("projectIdx", (item.getIndex()+1)+"");
				item.add(projIdx);
				Label mileLabel = new Label("milestone", new Model<String>((row.get("CURR_MILESTONE")==null?"":row.get("CURR_MILESTONE"))+"阶段"));
				item.add(mileLabel);
				Label deptLabel = new Label("dept", new PropertyModel(item.getModel(), "DEPT_NAME"));
				item.add(deptLabel);
				
				if(StringUtils.isEmpty((String)row.get("FATHER_PROID"))) {
					item.add(new ExternalLink("projectName", new PropertyModel(item.getModel(), "TASK_ADDR"), new PropertyModel(item.getModel(), "PROJ_NAME")));
				}
				else {
					item.add(new ExternalLink("projectName", null, "[子项目]"+row.get("PROJ_NAME")));
					deptLabel.setDefaultModel(new Model<String>("属于["+getMainService().getProjName((String)row.get("FATHER_PROID"))+"]"));
					
					mileLabel.setVisible(false);
				}
				
				final WebMarkupContainer userProjDetail = new WebMarkupContainer("userProjDetail");
				userProjDetail.setOutputMarkupId(true);
				
				final List<Map> userProjDetailList = new ArrayList<Map>();
				PageableListView listview = new PageableListView("userProjDetailList", userProjDetailList, 5) {
					protected void populateItem(final ListItem detailItem) {
						
						detailItem.add(new Label("REG_DATE", new PropertyModel(detailItem.getModel(), "REG_DATE")));
						detailItem.add(new Label("HOUR_COST", new PropertyModel(detailItem.getModel(), "HOUR_COST")));
						detailItem.add(new MultiLineLabel("REG_MEMO", new PropertyModel(detailItem.getModel(), "REG_MEMO")));
					}
					
				};
				userProjDetail.add(listview);
				userProjDetail.add(new AjaxPagingNavigator("navigator", listview));
				userProjDetail.setVersioned(false);
				
				item.add(new AjaxLink("userProjDetailLink"){

					@Override
					public void onClick(AjaxRequestTarget target) {
						userProjDetailList.clear();
						String beginDateStr = beginDate.getModelObject() == null ? "" : (String)beginDate.getModelObject();
						String endDateStr = endDate.getModelObject() == null ? "" : (String)endDate.getModelObject();
						
						String criteria = "u.user_id = '"+new PropertyModel(item.getModel(), "USER_ID").getObject()+"' and u.project_id = '"+new PropertyModel(item.getModel(), "PROJECT_ID").getObject()+"'";
						if(StringUtils.isNotBlank(beginDateStr)) {
							criteria += " and u.reg_date >= '"+beginDateStr+"'";
						}
						if(StringUtils.isNotBlank(endDateStr)) {
							criteria += " and u.reg_date <= '"+endDateStr+"'";
						}
						
						String sql = ExpressionUtil.parse(userProjCostDetailSql, UtilsMisc.toMap("criteria", criteria));
						
						List udList = getMainService().getJdbcTemplate().queryForList(sql);
						userProjDetailList.addAll(udList);
					
						target.addComponent(userProjDetail);
						target.appendJavascript("$('#"+"userProjDetailLink"+(item.getIndex()+1)+"').next().slideDown('fast');");
					}
					
				}.setOutputMarkupId(true).setMarkupId("userProjDetailLink"+(item.getIndex()+1)));
				
				item.add(userProjDetail);
			}
			
		});
		add(projStatListPanel);
		
		f.add(feedbackPanel);
		
		f.add(beginDate);
		f.add(endDate);
		
		final WebMarkupContainer deptPanel = new WebMarkupContainer("deptPanel");
		final DeptChoice depts = new DeptChoice("depts", getMainService().getJdbcTemplate(), getUser().getDeptId());
		depts.setOutputMarkupId(true);
		deptPanel.setOutputMarkupId(true);
		deptPanel.setVisible(false);
		final StaffChoice staffs = new StaffChoice("staffs");
		staffs.setOutputMarkupId(true);
		
		if(SecurityFacade.isManager()) {
			staffs.getStaffDirectly(getMainService().getJdbcTemplate(), "dept_id in ('"+StringUtils.join(getMainService().getSubDepts(getUser().getDeptId()), "','")+"') order by name");
		}
		
		if(!SecurityFacade.isManager()) {
			staffs.getStaffDirectly(getMainService().getJdbcTemplate(), "user_id = '"+getUser().getUserId()+"'");
		}
		
		
		
		OnChangeAjaxBehavior changeDept = new OnChangeAjaxBehavior() {
			protected void onUpdate(AjaxRequestTarget target) {
				String deptId = depts.getModelValue();
				staffs.getUsersByDept(getMainService().getJdbcTemplate(), deptId);
				target.addComponent(staffs);
			}
			
		};
		
		f.add(new AjaxSubmitButton("statButt") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				String userId = staffs.getModelValue();
				String beginDateStr = beginDate.getModelObject() == null ? "" : (String)beginDate.getModelObject();
				String endDateStr = endDate.getModelObject() == null ? "" : (String)endDate.getModelObject();
				projStatList.clear();	
				
				if(StringUtils.isNotBlank(userId) && !"-1".equals(userId)) {
					String userName = staffs.getStaffName(userId);
					
					String criteria = "u.user_id = '"+userId+"'";
					
					if(StringUtils.isNotBlank(beginDateStr)) {
						criteria += " and u.reg_date >= '"+beginDateStr+"'";
					}
					if(StringUtils.isNotBlank(endDateStr)) {
						criteria += " and u.reg_date <= '"+endDateStr+"'";
					}
					
					Map paramMap = UtilsMisc.toMap("criteria", criteria);
					String sql = ExpressionUtil.parse(getMainService().getUserProjCostStatSql(), paramMap);
					
					projStatList.addAll(getMainService().getJdbcTemplate().queryForList(sql));
					
					Double totalHour = 0.0d;
					for (Map map : projStatList) {
						totalHour += ((Number)map.get("HOUR_COST")).doubleValue();
					}
					selectedDate.setDefaultModelObject(""+userName+"<" + beginDateStr +"至"+endDateStr+">共<"+UtilsMisc.transHour(totalHour)+">天");
				}
				else {
					selectedDate.setDefaultModelObject("<" + beginDateStr +"至"+endDateStr+">");
					error("请选择人员");
				}
				target.addComponent(projStatListPanel);
				target.addComponent(selectedDate);
				target.addComponent(feedbackPanel);
				target.appendJavascript("$('.important').hide();");
			}
			
		});
		f.add(new AjaxSubmitButton("clearStatButt"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				projStatList.clear();	
			
				String beginDateStr = beginDate.getModelObject() == null ? "" : (String)beginDate.getModelObject();
				String endDateStr = endDate.getModelObject() == null ? "" : (String)endDate.getModelObject();
				selectedDate.setDefaultModelObject("<" + beginDateStr +"至"+endDateStr+">");
				
				target.addComponent(projStatListPanel);
				target.addComponent(selectedDate);
			}
			
		});
		
		depts.add(changeDept);
		deptPanel.add(depts);
        f.add(deptPanel);
        f.add(staffs);
		add(f);
		
	}
	
	
	
	private void addStatUser(List<Map> userStatList, Map userInfo) {
	}
}
